/**
 * 添加或者修改页面
 */
var HxStorageTransferInfoDlg = {
    data: {
        transferDate: "",
        outWarehouseId: "",
        outWarehouseName: "",
        putWarehouseId: "",
        putWarehouseName: "",
        goodsId: "",
        goodsName: "",
        goodsNumber: "",
        goodsPcode69: "",
        goodsSpecs: "",
        kcUnit: "",
        outPositionId: "",
        outPositionNumber: "",
        num: "",
        putPositionId: "",
        putPositionNumber: "",
        deptId: "",
        deliverId: "",
        note: "",
        createTimes: "",
        createName: "",
        v1: "",
        v2: ""
    }
};
/**
 * 添加或者修改页面
 */
var BasicPositionInfoDlg = {
    data: {
    	id: "",
        positionNumber: "",
        positionAreaId: ""
    }
};
/**
 * 详情对话框
 */
var HxStorageStockInfoDlg = {
    data: {
    	id:"",
        positionId: "",
        positionNumber: "",
        goodsId: "",
        goodsName: "",
        goodsNumber: "",
        goodsPcode69: "",
        goodsSpecs: "",
        kcUnit: "",
        kcNum: "",
        jibenNum: "",
        jibenUnit: "",
        cgNum: "",
        cgUnit: "",
        pfNum: "",
    }
};
layui.use(['form', 'admin', 'ax','laydate'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;

    laydate.render({
    	elem:'#transferDate'
        	,value:new Date()
    });

    //让当前iframe弹层高度适应
    admin.iframeAuto();

    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        var ajax = new $ax(Feng.ctxPath + "/hxStorageTransfer/addItem", function (data) {
        	if(data.success){
	            Feng.success("添加成功！");
	            window.location.href = Feng.ctxPath + '/hxStorageTransfer'
        	} else {
	            Feng.error("添加失败！" + data.message);
        	}
        }, function (data) {
            Feng.error("添加失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.start();

        return false;
    });
    
    $('#choiceOutPositionNumber').click(function () {
    	var outWarehouseId = $("#outWarehouseId").val();
    	var putWarehouseId = $("#putWarehouseId").val();
    	if (outWarehouseId==null||outWarehouseId==''||putWarehouseId==null||putWarehouseId=='') {
    		layer.msg('请选择转出、转入仓库'); 
		} else {
	        layer.open({
	            type: 2,
	            title: '选择转出库位',
	            area: ['1100px', '560px'],
	            content: Feng.ctxPath + '/hxStorageStock/tochoiceStorageStock?warehouseId='+outWarehouseId,
	            end: function () {
	                $("#storageStockId").val(HxStorageStockInfoDlg.data.id);
	                $("#outPositionId").val(HxStorageStockInfoDlg.data.positionId);
	                $("#outPositionNumber").val(HxStorageStockInfoDlg.data.positionNumber);
	                $("#goodsId").val(HxStorageStockInfoDlg.data.goodsId);
	                $("#goodsName").val(HxStorageStockInfoDlg.data.goodsName);
	                $("#goodsNumber").val(HxStorageStockInfoDlg.data.goodsNumber);
	                $("#goodsPcode69").val(HxStorageStockInfoDlg.data.goodsPcode69);
	                $("#goodsSpecs").val(HxStorageStockInfoDlg.data.goodsSpecs);
	                $("#kcunit").val(HxStorageStockInfoDlg.data.kcUnit);
	                $("#num").val(HxStorageStockInfoDlg.data.kcNum);
                    $("#kcunit").empty();
                    $.ajax({
                        url: `/rest/HxStorageReturn/detailedGoodsId?goodsId=${HxStorageStockInfoDlg.data.goodsId}`,
                        type: 'GET',
                        async: false, // 使用同步请求
                        success: function (response) {
                            console.log(response); // 输出结果
                            let units = [];
                            if (response && response.data && response.data.length > 0) {
                                const lists = response.data.map(item => {
                                    const unitProps = [item.kcUnit,item.jibenUnit, item.cgUnit, item.pfUnit, item.psUnit];
                                    return [...new Set(unitProps.filter(unit => unit !== null && unit !== undefined))];
                                });
                                units = lists.flat();
                            }
                            console.log(units); // 输出单位数组

                            // 将单位添加到下拉列表中
                            units.forEach(unit => {
                                $("#kcunit").append(new Option(unit, unit));
                            });

                            form.render("select");
                        },
                    });
	                if(HxStorageStockInfoDlg.data.id != "" && HxStorageStockInfoDlg.data.id != null){
					    //获取详情信息，填充表单
					    var ajax = new $ax(Feng.ctxPath + "/hxStorageTransfer/detailbd?warehouseId=" + putWarehouseId + "&goodsId=" + HxStorageStockInfoDlg.data.goodsId);
					    var result = ajax.start();
					    if(result.data != "" && result.data != null){
			                $("#putPositionId").val(result.data.positionId);
			                $("#putPositionNumber").val(result.data.positionNumber);
					    }
	                }
	            }
	        });
		}
    });
    form.on('select(kcunit)', function(){
        // let unitType = $("#unitType").val();
        var goodsName = $("#goodsName").val();
        let unitVal = $("#kcunit").val();
        console.log(unitVal);
        //根据单位名称获取对应的换算率
        let unitRate = unitInfo[unitVal];
        //设置对应的换算率
        $("#rate").val(unitRate);
        //根据商品名称获取对应的单位
        if (goodsName == null || goodsName == '') {

        } else {
            var goodsVolume = HxBasicGoodsInfoDlg.data.goodsVolume
            var goodsWeight = HxBasicGoodsInfoDlg.data.goodsWeight
            var goodsSupportvolume = HxBasicGoodsInfoDlg.data.goodsSupportvolume
            var goodsChargingCg = HxBasicGoodsInfoDlg.data.goodsChargingCg
            if(parseFloat(unitRate) == parseFloat(goodsInfo['cgUnit'].rate)){
                $("#goodsVolume").val(goodsVolume);
                $("#goodsWeight").val(goodsWeight);
                $("#goodsSupportvolume").val(goodsSupportvolume);
            }
            if(parseFloat(unitRate) < parseFloat(goodsInfo['cgUnit'].rate)){
                //如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
                var div = accDiv(goodsInfo['cgUnit'].rate,unitRate)
                var divv_v = accDiv(goodsVolume,div).toFixed(4)
                $("#goodsVolume").val(divv_v);
                var divv_w = accDiv(goodsWeight,div).toFixed(3)
                $("#goodsWeight").val(divv_w);
                var divv_s = accMul(goodsSupportvolume, div)
                $("#goodsSupportvolume").val(divv_s);
            }
            if(parseFloat(unitRate) > parseFloat(goodsInfo['cgUnit'].rate)){
                //如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
                var div = accDiv(unitRate,goodsInfo['cgUnit'].rate)
                var divm_v = accMul(goodsVolume,div).toFixed(4)
                $("#goodsVolume").val(divm_v);
                var divm_w = accMul(goodsWeight,div).toFixed(3)
                $("#goodsWeight").val(divm_w);
                var divv_s = accDiv(goodsSupportvolume, div)
                $("#goodsSupportvolume").val(divv_s);
            }
            //换算单价
            $("#goodsPrice").val(accMul(unitRate,goodsChargingCg).toFixed(3));
            let psNum = $("#sumNum").val();//应入数量
            let goodsPrice = $("#goodsPrice").val();//单价
            //重新计算
            $("#putMoney").val(accMul(psNum,goodsPrice).toFixed(3));//改变金额
            $("#putVolume").val(accMul(psNum,goodsVolume).toFixed(4));//改变应入体积
            $("#putWeight").val(accMul(psNum,goodsWeight).toFixed(3));//改变应入重量
        }
    });
    $('#choicePutPositionNumber').click(function () {
    	var outWarehouseId = $("#outWarehouseId").val();
    	var putWarehouseId = $("#putWarehouseId").val();
    	if (outWarehouseId==null||outWarehouseId==''||putWarehouseId==null||putWarehouseId=='') {
    		layer.msg('请选择转入、转出仓库'); 
		} else {
	        layer.open({
	            type: 2,
	            title: '选择转入库位',
	            area: ['1000px', '500px'],
	            content: Feng.ctxPath + '/basicPosition/tochoicePositionHx?warehouseId='+putWarehouseId,
	            end: function () {
	                $("#putPositionId").val(BasicPositionInfoDlg.data.id);
	                $("#putPositionNumber").val(BasicPositionInfoDlg.data.positionNumber);
	            }
	        });
		}
    });

    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + '/hxStorageTransfer'
    });

});